package com.guigu.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.junit.Test;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JDBCutils {
	private static DataSource source;
	static
	{
		try {
			InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
			Properties pros = new Properties();
			pros.load(is);
			source = DruidDataSourceFactory.createDataSource(pros);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 通用增删改操作 
	 * @throws Exception 
	 */
	
	 public static void update(String sql,Object ...args){
		 Connection conn = null;
		 PreparedStatement ps = null;
		 try {
			 conn = getConnection();
			 ps = conn.prepareStatement(sql);
			 for(int i=0;i<args.length;i++)
			 {
				 ps.setObject(i+1, args[i]);
			 }
			 ps.execute();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			DbUtils.closeQuietly(conn);
			DbUtils.closeQuietly(ps);
		}
	 }
		
	 
	/**
	 * 使用Druid数据库连接池获取连接
	 * @return
	 * @throws Exception
	 */
	public static Connection getConnection() throws Exception
	{
		Connection conn = source.getConnection();
		return conn;
	}

}
